package org.rsbot.gui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.SystemTray;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import org.rsbot.bot.Bot;
import org.rsbot.bot.RSLoader;
import org.rsbot.log.TextAreaLogHandler;
import org.rsbot.script.Script;
import org.rsbot.script.ScriptManifest;
import org.rsbot.script.internal.ScriptHandler;
import org.rsbot.script.internal.event.ScriptListener;
import org.rsbot.script.methods.Game;
import org.rsbot.script.methods.MethodContext;
import org.rsbot.script.util.WindowUtil;
import org.rsbot.util.GlobalConfiguration;
import org.rsbot.util.GlobalConfiguration.OperatingSystem;
import org.rsbot.util.GlobalConfiguration.Paths;
import org.rsbot.util.Minimizer;
import org.rsbot.util.ScreenshotUtil;
import org.rsbot.util.Serializer;
import org.rsbot.util.UpdateUtil;

public class BotGUI extends JFrame
  implements ActionListener, ScriptListener
{
  public static final int PANEL_WIDTH = 765;
  public static final int PANEL_HEIGHT = 503;
  public static final int LOG_HEIGHT = 120;
  private static final long serialVersionUID = -5411033752001988794L;
  private BotPanel panel;
  private BotToolBar toolBar;
  private BotMenuBar menuBar;
  private JScrollPane textScroll;
  private BotHome home;
  private JFrame frame = this;
  private List<Bot> bots = new ArrayList();
  private String theme_name = null;
  private static final Logger log = Logger.getLogger(BotGUI.class.getName());

  public BotGUI() {
    init();
    pack();
    setTitle(null);
    setLocationRelativeTo(getOwner());
    setMinimumSize(getSize());
    setResizable(true);
    this.theme_name = null;

    Object localObject = Serializer.deserialize(new File("theme.pb"));
    this.theme_name = (localObject == null ? "SubstanceTwilightLookAndFeel" : (String)localObject);
    SwingUtilities.invokeLater(new Runnable()
    {
      public void run() {
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
        ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);

        if (GlobalConfiguration.RUNNING_FROM_JAR) {
          UpdateUtil localUpdateUtil = new UpdateUtil(BotGUI.this);
          localUpdateUtil.checkUpdate(false);
        }
      }
    });
    new SplashAd(this);
  }

  public void setTitle(String paramString)
  {
    if (paramString != null) {
      super.setTitle(paramString + " - " + "RSBot" + " v" + GlobalConfiguration.getVersion() / 100.0F);
    }
    else
      super.setTitle("RSBot v" + GlobalConfiguration.getVersion() / 100.0F);
  }

  public void actionPerformed(ActionEvent paramActionEvent)
  {
    String str1 = paramActionEvent.getActionCommand();

    int i = str1.indexOf(46);
    String str2;
    String str3;
    if (i == -1) {
      str2 = str1;
      str3 = "";
    } else {
      str2 = str1.substring(0, i);
      str3 = str1.substring(i + 1);
    }
    if (str2.equals("Close")) {
      int j = Integer.parseInt(str3);
      removeBot((Bot)this.bots.get(j - 1));
    }
    else
    {
      Bot localBot;
      if (str2.equals("File")) {
        if (str3.equals("New Bot")) {
          addBot();
        } else if (str3.equals("Close Bot")) {
          removeBot(getCurrentBot());
        } else if (str3.equals("Run Script")) {
          localBot = getCurrentBot();
          if (localBot != null)
            showScriptSelector(localBot);
        }
        else if (str3.equals("Stop Script")) {
          localBot = getCurrentBot();
          if (localBot != null)
            showStopScript(localBot);
        }
        else if (str3.equals("Pause Script")) {
          localBot = getCurrentBot();
          if (localBot != null)
            pauseScript(localBot);
        }
        else if (str3.equals("Snap to Tray")) {
          localBot = getCurrentBot();
          if (localBot != null)
            try {
              if (!SystemTray.isSupported()) {
                JOptionPane.showMessageDialog(this, "System-Tray feature is not supported by your OS.", "Error", 0);
                return;
              }
              setVisible(false);
              Minimizer.snapToTray(this);
            }
            catch (Exception localException) {
            }
        }
        else if (str3.equals("Save Screenshot")) {
          localBot = getCurrentBot();
          if (localBot != null)
            ScreenshotUtil.saveScreenshot(localBot, localBot.getMethodContext().game.isLoggedIn());
        }
        else if (str3.equals("Exit")) {
          System.exit(0);
        }
      }
      else
      {
        boolean bool1;
        if (str2.equals("Edit")) {
          if (str3.equals("Accounts")) {
            AccountManager.getInstance().showGUI();
          } else {
            localBot = getCurrentBot();
            if (localBot != null)
              if (str3.equals("Force Input")) {
                bool1 = ((JCheckBoxMenuItem)paramActionEvent.getSource()).isSelected();
                localBot.overrideInput = bool1;
                this.toolBar.setOverrideInput(bool1);
              } else if (str3.equals("Less CPU")) {
                localBot.disableRendering = ((JCheckBoxMenuItem)paramActionEvent.getSource()).isSelected();
              } else if (str3.equals("Disable Anti-Randoms")) {
                localBot.disableRandoms = ((JCheckBoxMenuItem)paramActionEvent.getSource()).isSelected();
              } else if (str3.equals("Disable Auto Login")) {
                localBot.disableAutoLogin = ((JCheckBoxMenuItem)paramActionEvent.getSource()).isSelected();
              }
          }
        }
        else if (str2.equals("View")) {
          localBot = getCurrentBot();
          bool1 = ((JCheckBoxMenuItem)paramActionEvent.getSource()).isSelected();
          if (str3.equals("Hide Toolbar")) {
            toggleViewState(this.toolBar, bool1);
          } else if (str3.equals("Hide Log Window")) {
            toggleViewState(this.textScroll, bool1);
          } else if (localBot != null)
          {
            Object localObject;
            if (str3.equals("All Debugging")) {
              for (localObject = BotMenuBar.DEBUG_MAP.keySet().iterator(); ((Iterator)localObject).hasNext(); ) { String str4 = (String)((Iterator)localObject).next();
                Class localClass = (Class)BotMenuBar.DEBUG_MAP.get(str4);
                boolean bool3 = this.menuBar.getCheckBox(str4).isSelected();
                this.menuBar.getCheckBox(str4).setSelected(bool1);
                if (bool1) {
                  if (!bool3) {
                    localBot.addListener(localClass);
                  }
                }
                else if (bool3)
                  localBot.removeListener(localClass);
              }
            }
            else
            {
              localObject = (Class)BotMenuBar.DEBUG_MAP.get(str3);
              this.menuBar.getCheckBox(str3).setSelected(bool1);
              if (bool1) {
                localBot.addListener((Class)localObject);
              } else {
                this.menuBar.getCheckBox("All Debugging").setSelected(false);
                localBot.removeListener((Class)localObject);
              }
            }
          }
        } else if (str2.equals("Help")) {
          if (str3.equals("Site"))
            openURL("http://www.powerbot.org");
          else if (str3.equals("Project"))
            openURL("http://code.google.com/p/rsbot-client");
          else if (str3.equals("About")) {
            JOptionPane.showMessageDialog(this, new String[] { "An open source bot,currently developed by Nader Sleiman as \nLead developer and his team of devs and contributers.", "Visit http://www.powerbot.org/ for more information." }, "About", 1);
          }

        }
        else if (str2.equals("Layout")) {
          if (str3.equals("Themes"))
          {
            if (ThemesGui.isUpdated())
              log.info("The bot just updated dependancies, please restart the bot before you select themes.");
            else if (ThemesGui.isProcessing())
              log.info("its currently downloading dependancies, please wait ...");
            else {
              log.info("Wait for next release for a better implementation");
            }
          }

        }
        else if (str2.equals("Tab")) {
          localBot = getCurrentBot();
          this.menuBar.setBot(localBot);
          this.panel.setBot(localBot);
          this.panel.repaint();
          this.toolBar.setHome(localBot == null);
          if (localBot == null) {
            setTitle(null);
            this.toolBar.setScriptButton(0);
            this.toolBar.setOverrideInput(false);
            this.toolBar.setInputState(3);
          } else {
            setTitle(localBot.getAccountName());
            Map localMap = localBot.getScriptHandler().getRunningScripts();
            if (localMap.size() > 0) {
              if (((Script)localMap.values().iterator().next()).isPaused())
                this.toolBar.setScriptButton(2);
              else
                this.toolBar.setScriptButton(1);
            }
            else {
              this.toolBar.setScriptButton(0);
            }
            this.toolBar.setOverrideInput(localBot.overrideInput);
            this.toolBar.setInputState(localBot.inputFlags);
          }
        } else if (str2.equals("Run")) {
          localBot = getCurrentBot();
          if (localBot != null)
            showScriptSelector(localBot);
        }
        else if ((str2.equals("Pause")) || (str2.equals("Resume"))) {
          localBot = getCurrentBot();
          if (localBot != null)
            pauseScript(localBot);
        }
        else if (str2.equals("Input")) {
          localBot = getCurrentBot();
          if (localBot != null) {
            boolean bool2 = !localBot.overrideInput;
            localBot.overrideInput = bool2;
            this.menuBar.setOverrideInput(bool2);
            this.toolBar.setOverrideInput(bool2);
            this.toolBar.updateInputButton();
          }
        }
      }
    }
  }

  public BotPanel getPanel() {
    return this.panel;
  }

  public Bot getBot(Object paramObject) {
    ClassLoader localClassLoader = paramObject.getClass().getClassLoader();
    for (Bot localBot : this.bots) {
      if (localClassLoader == localBot.getLoader().getClient().getClass().getClassLoader()) {
        this.panel.offset();
        return localBot;
      }
    }
    return null;
  }

  public void addBot() {
    Bot localBot = new Bot();
    this.bots.add(localBot);
    this.toolBar.addTab();
    localBot.getScriptHandler().addScriptListener(this);
    new Thread(new Runnable(localBot)
    {
      public void run() {
        this.val$bot.start();
        BotGUI.this.home.setBots(BotGUI.this.bots);
      }
    }).start();
  }

  public void removeBot(Bot paramBot)
  {
    int i = this.bots.indexOf(paramBot);
    if (i >= 0) {
      this.toolBar.removeTab(i + 1);
    }
    this.bots.remove(i);
    paramBot.getScriptHandler().stopAllScripts();
    paramBot.getScriptHandler().removeScriptListener(this);
    this.home.setBots(this.bots);
    new Thread(new Runnable(paramBot)
    {
      public void run() {
        this.val$bot.stop();
        System.gc();
      }
    }).start();
  }

  void pauseScript(Bot paramBot)
  {
    ScriptHandler localScriptHandler = paramBot.getScriptHandler();
    Map localMap = localScriptHandler.getRunningScripts();
    if (localMap.size() > 0) {
      int i = ((Integer)localMap.keySet().iterator().next()).intValue();
      localScriptHandler.pauseScript(i);
    }
  }

  private Bot getCurrentBot() {
    int i = this.toolBar.getCurrentTab() - 1;
    if (i >= 0) {
      return (Bot)this.bots.get(i);
    }
    return null;
  }

  private void showScriptSelector(Bot paramBot) {
    if (AccountManager.getAccountNames().length == 0) {
      JOptionPane.showMessageDialog(this, "No accounts found! Please create one before using the bot.");
      AccountManager.getInstance().showGUI();
    } else if (paramBot.getMethodContext() == null) {
      JOptionPane.showMessageDialog(this, "The client is not currently loaded!");
    } else {
      new ScriptSelector(this, paramBot).showGUI();
    }
  }

  private void showStopScript(Bot paramBot) {
    ScriptHandler localScriptHandler = paramBot.getScriptHandler();
    Map localMap = localScriptHandler.getRunningScripts();
    if (localMap.size() > 0) {
      int i = ((Integer)localMap.keySet().iterator().next()).intValue();
      Script localScript = (Script)localMap.get(Integer.valueOf(i));
      ScriptManifest localScriptManifest = (ScriptManifest)localScript.getClass().getAnnotation(ScriptManifest.class);
      int j = JOptionPane.showConfirmDialog(this, "Would you like to stop the script " + localScriptManifest.name() + "?", "Script", 2, 3);

      if (j == 0) {
        localScriptHandler.stopScript(i);
        this.toolBar.setScriptButton(0);
      }
    }
  }

  private void toggleViewState(Component paramComponent, boolean paramBoolean) {
    Dimension localDimension = getSize();
    localDimension.height += paramComponent.getSize().height * (paramBoolean ? -1 : 1);
    paramComponent.setVisible(!paramBoolean);
    setMinimumSize(localDimension);
    if ((getExtendedState() & 0x6) != 6)
      pack();
  }

  private void init()
  {
    setDefaultCloseOperation(0);

    addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent paramWindowEvent) {
        BotGUI.this.dispose();
        System.exit(0);
      }
    });
    setIconImage(GlobalConfiguration.getImage("/resources/images/icon.png", GlobalConfiguration.Paths.ICON));

    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    try
    {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch (Exception localException) {
    }
    WindowUtil.setFrame(this);

    this.home = new BotHome();
    this.panel = new BotPanel(this.home);
    this.toolBar = new BotToolBar(this);
    this.menuBar = new BotMenuBar(this);
    this.panel.setFocusTraversalKeys(0, new HashSet());
    this.toolBar.setHome(true);
    this.menuBar.setBot(null);
    setJMenuBar(this.menuBar);

    this.textScroll = new JScrollPane(TextAreaLogHandler.TEXT_AREA, 22, 31);

    this.textScroll.setBorder(null);
    this.textScroll.setPreferredSize(new Dimension(765, 120));
    this.textScroll.setVisible(true);

    add(this.toolBar, "North");
    add(this.panel, "Center");
    add(this.textScroll, "South");
  }

  private void openURL(String paramString) {
    GlobalConfiguration.OperatingSystem localOperatingSystem = GlobalConfiguration.getCurrentOperatingSystem();
    try
    {
      Object localObject;
      Method localMethod;
      if (localOperatingSystem == GlobalConfiguration.OperatingSystem.MAC) {
        localObject = Class.forName("com.apple.eio.FileManager");
        localMethod = ((Class)localObject).getDeclaredMethod("openURL", new Class[] { String.class });
        localMethod.invoke(null, new Object[] { paramString });
      } else if (localOperatingSystem == GlobalConfiguration.OperatingSystem.WINDOWS) {
        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + paramString);
      } else {
        localObject = new String[] { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
        localMethod = null;
        for (int i = 0; (i < localObject.length) && (localMethod == null); i++) {
          if (Runtime.getRuntime().exec(new String[] { "which", localObject[i] }).waitFor() == 0) {
            localMethod = localObject[i];
          }
        }
        if (localMethod == null) {
          throw new Exception("Could not find web browser");
        }
        Runtime.getRuntime().exec(new String[] { localMethod, paramString });
      }
    }
    catch (Exception localException) {
      JOptionPane.showMessageDialog(this, "Error Opening Browser", "Error", 0);
    }
  }

  public void scriptStarted(ScriptHandler paramScriptHandler, Script paramScript) {
    EventQueue.invokeLater(new Runnable(paramScriptHandler)
    {
      public void run()
      {
        Bot localBot = this.val$handler.getBot();
        if (localBot == BotGUI.this.getCurrentBot()) {
          localBot.inputFlags = 2;
          localBot.overrideInput = false;
          BotGUI.this.toolBar.setScriptButton(1);
          BotGUI.this.toolBar.setInputState(localBot.inputFlags);
          BotGUI.this.toolBar.setOverrideInput(false);
          BotGUI.this.menuBar.setOverrideInput(false);
          String str = localBot.getAccountName();
          BotGUI.this.toolBar.setTabLabel(BotGUI.this.bots.indexOf(localBot) + 1, str == null ? "RuneScape" : str);
          BotGUI.this.toolBar.updateInputButton();
          BotGUI.this.setTitle(str);
        }
      } } );
  }

  public void scriptStopped(ScriptHandler paramScriptHandler, Script paramScript) {
    Bot localBot = paramScriptHandler.getBot();
    if (localBot == getCurrentBot()) {
      localBot.inputFlags = 3;
      localBot.overrideInput = false;
      this.toolBar.setScriptButton(0);
      this.toolBar.setInputState(localBot.inputFlags);
      this.toolBar.setOverrideInput(false);
      this.menuBar.setOverrideInput(false);
      this.menuBar.setPauseScript(false);
      this.toolBar.setTabLabel(this.bots.indexOf(localBot) + 1, "RuneScape");
      this.toolBar.updateInputButton();
      setTitle(null);
    }
  }

  public void scriptResumed(ScriptHandler paramScriptHandler, Script paramScript) {
    if (paramScriptHandler.getBot() == getCurrentBot()) {
      this.toolBar.setScriptButton(1);
      this.menuBar.setPauseScript(false);
    }
  }

  public void scriptPaused(ScriptHandler paramScriptHandler, Script paramScript) {
    if (paramScriptHandler.getBot() == getCurrentBot()) {
      this.toolBar.setScriptButton(2);
      this.menuBar.setPauseScript(true);
    }
  }

  public void inputChanged(Bot paramBot, int paramInt) {
    paramBot.inputFlags = paramInt;
    this.toolBar.setInputState(paramInt);
    this.toolBar.updateInputButton();
  }
}